/**
 * @description: 背景音乐播放组件
 * @update: 2019-11-11
 * @version: 1.2
 **/

(function(win) {

    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

    var head = document.getElementsByTagName('head')[0],
        link = document.createElement('link');
    link.href = '/act/all/cdn/music/1.2/music.css';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    head.appendChild(link);

    var MusicPlay = function(options) {
        if (!options.url) {
            return alert('请填写音乐路径');
        }

        var _options = {
            autoPlay: false,
            url: '',
            parent: document.querySelector('body'),
            color: '#fff',
            size: 50,
            top: 20,
            right: 20,
            bottom: 'auto',
            left: 'auto',
            hint: true
        };

        for (var name in options) {
            _options[name] = options[name];
        }

        // 设定父元素为相对定位
        _options.parent.style.position = 'relation';

        // 音乐图标
        var $btnIcon = $('<a href="javascript:;" class="icon_cy music_icon">&#xe602;</a>').css({
            width: _options.size,
            height: _options.size,
            lineHeight: _options.size + 'px',
            left: _options.left,
            right: _options.right,
            top: _options.top,
            bottom: _options.bottom,
            color: _options.color,
            borderColor: _options.color
        }).appendTo(_options.parent);

        // 音乐图标 “禁止线”
        var $line = $('<span class="music_line"></span>')
            .css({borderColor: _options.color})
            .appendTo($btnIcon);

        var $hint = $('<span class="music_hint">')
            .css({
                top: _options.size + 10,
                display: 'none'
            })
            .html(typeof _options.hint === 'string' ? _options.hint : '点击这里播放背景音乐哦~')
            .appendTo($btnIcon);

        var triangle = $('<i class="music_triangle"/>').appendTo($hint);

        // 音乐播放
        var $audio = $('<audio src=' + _options.url + ' class="music_bg" hidden preload="auto" loop>')
            .appendTo(_options.parent);
        var audio = $audio[0];
        var window_init = true;

        function audioResult(flag) {
            $hint.hide();
            _options.autoPlay = flag;
            if (flag) {
                try{
                    // 主流浏览器兼容
                    audio.play().then(function() {
                        $btnIcon.addClass('music_start').removeClass('music_stop');
                    }).catch(function (err) {
                        _options.hint && $hint.show();
                    });
                }catch (e) {
                    // IE 内核
                    $btnIcon.addClass('music_start').removeClass('music_stop');
                    audio.play()
                }
                if (!audio.paused) {
                    window_init = false;
                }
            } else {
                $btnIcon.addClass('music_stop').removeClass('music_start');
                audio.pause();
            }
        }

        this.audioResult = audioResult;

        $btnIcon.click(function (e) {
            audioResult(window_init || !_options.autoPlay);
        });

        if (_options.autoPlay) {
            if (isMobile) {
                // 创建页面监听，等待微信端页面加载完毕 触发音频播放
                document.addEventListener('DOMContentLoaded', function () {
                    audioResult(true);
                    document.addEventListener("WeixinJSBridgeReady", function () {
                        audioResult(true);
                    }, false);
                });
                // 创建触摸监听，当浏览器打开页面时，触摸屏幕触发事件，进行音频播放
                $btnIcon.on('touchstart', function (e) {
                    e.stopPropagation();
                });
                document.addEventListener('touchstart', function () {
                    if (window_init) {
                        audioResult(true);
                    }
                });
            } else {
                audio.oncanplaythrough = function () {
                    audioResult(true);
                }
            }
        } else {
            audioResult();
        }
    };

    MusicPlay.fn = MusicPlay.prototype = {
        stop: function() {
            this.audioResult(false);
        },
        start: function() {
            this.audioResult(true);
        }
    };

    win.MusicPlay = MusicPlay;

})(window);
